package com.example.tccspeech;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.annotation.SuppressLint;
import android.content.Context;
import android.webkit.WebView;
import android.webkit.WebViewClient;

@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
public class Translator {

    // Credentials for Bing Translate Service
    private static final String BING_TRANSLATE_CLIENT_ID     = "TranslateTCCAppID";
    private static final String BING_TRANSLATE_CLIENT_SECRET = "WTFWY0FmZkp8kzN00VDWRHgo/ccg0wFehxpMFHPib0w=";

    Context                     mContext;
    TranslateListener           mListener;

    public void setTranslationListener(TranslateListener listener) {
        mListener = listener;
    }

    public Translator(Context context) {
        mContext = context;
    }

    public void translate(String text) {
        translateFromWebInterface(text);
    }

    // private String translateUsingBing(String text) throws Exception {
    //
    // // Set the Client ID / Client Secret once per JVM. It is set statically and applies to all services
    // Translate.setClientId(BING_TRANSLATE_CLIENT_ID);
    // Translate.setClientSecret(BING_TRANSLATE_CLIENT_SECRET);
    //
    // String translatedText = "";

    // // English AUTO_DETECT
    // translatedText = Translate.execute(text, mOutputLanguage);
    // return translatedText;
    // }
    //
    // }

    private void translateFromWebInterface(String text) {

        final WebView webview = new WebView(mContext);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                webview.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
                // webview.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementById('result_box').innerHTML+'</head>');");
            }
        });

        webview.loadUrl(createUrlAdress(text));
    }

    class MyJavaScriptInterface {

        public void processHTML(String html) {

            try {
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(new InputSource(new StringReader(html)));
                // Document doc = dBuilder.parse(html);
                // doc.getDocumentElement().normalize();
                // NodeList nList = doc.getElementsByTagName("item");
                Element element = doc.getElementById("result_box");
                NodeList nodeList = element.getElementsByTagName("span");
                for (int i = 0; i < nodeList.getLength(); i++) {
                    Node node = nodeList.item(i);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            mListener.receiveTranslation(html);
        }
    }

    private String createUrlAdress(String info) {

        String separator = "%20";
        String origin = "pt";
        String destination = "en";
        String value = " http://translate.google.com.br/#" + origin + "/" + destination + "/";

        String[] content = info.split(" ");
        value += content[0];
        for (int i = 1; i < content.length; i++) {
            value += (separator + content[i]);
        }
        return value;
    }

    public interface TranslateListener {
        public void receiveTranslation(String translation);
    }

}
